package tjs.study.notes.dotest.jdk.thread.reentrantLock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by Nicky.Tang on 2021/11/16 12:07 下午
 *
 * @since 02.12.10
 */
public class DoTestOfReadWriteLock {
    private static final ReentrantReadWriteLock REENTRANT_READ_WRITE_LOCK = new ReentrantReadWriteLock();
    private static final ReentrantReadWriteLock.WriteLock WRITE_LOCK = REENTRANT_READ_WRITE_LOCK.writeLock();
    private static final ReentrantReadWriteLock.ReadLock READ_LOCK = REENTRANT_READ_WRITE_LOCK.readLock();
    private static List<String> list = new ArrayList();
    public static final int i = 0;

    //读list
    public static void readList() {
        boolean lockFlas = false;
        try {
            System.out.println(Thread.currentThread().getName() + "前:" + list.size() + " :" );
            if(lockFlas = READ_LOCK.tryLock(100, TimeUnit.MILLISECONDS)){
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName() + "后:" + list.size() + " :" );
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
           if(lockFlas){
               READ_LOCK.unlock();
           }
        }
    }

    //写list
    public static void writeList() {
        try {
            WRITE_LOCK.lock();
            Thread.sleep(100);
            System.out.println(Thread.currentThread().getName() + ":新增1个元素");
            list.add("test " + i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            WRITE_LOCK.unlock();
        }
    }

    public static void main(String[] args) {

        final CountDownLatch countDownLatch = new CountDownLatch(10);
        new Thread(()->{
            try {
                countDownLatch.await();
                //执行目标方法
                writeList();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }).start();
        countDownLatch.countDown();
        for (int i = 0; i < 9; i++) {
            new Thread(()->{
                try {
                    countDownLatch.await();
                    //执行目标方法
                    readList();
                } catch (Throwable throwable) {
                    throwable.printStackTrace();
                }
            }).start();
            countDownLatch.countDown();
        }
    }
}
